import calendar
import logging
from datetime import datetime, timedelta

# import lunar as lunar
from flask_restful import fields, marshal_with, reqparse, Resource

from common.lunar import lunar_year, get_ludar_date, lunar_day1


def get_ludar_dict(tm):
    l_y, l_m, l_d = get_ludar_date(tm)
    dws = calendar.Calendar(0).itermonthdays2(tm.year, tm.month)
    ludar_date_list = []
    count = 0
    for (d, w) in dws:
        if d == 0:
            # continue
            if count < 7:
                delta = timedelta(days=datetime(tm.year, tm.month, 1).weekday() - w)
                d_tmp = datetime(tm.year, tm.month, 1) - delta
            else:
                delta = timedelta(
                    days=(w - datetime(tm.year, tm.month, calendar.monthrange(tm.year, tm.month)[1]).weekday()))
                d_tmp = datetime(tm.year, tm.month, calendar.monthrange(tm.year, tm.month)[1]) + delta
        else:
            d_tmp = datetime(tm.year, tm.month, d)
        (l_y, l_m, l_d) = get_ludar_date(d_tmp)
        is_today = (d_tmp - datetime.now()).days
        d_str = str(d_tmp.day)
        ludar_date_list.append(dict(c_d=d_str, l_d=lunar_day1(l_m, l_d), is_today=is_today))
        count += 1
    return dict(l_year=lunar_year(l_y), dates=ludar_date_list), 200


class Calendar(Resource):
    response_fields = {
        'l_year': fields.String,
        'dates': fields.List(
            fields.Nested({
                'c_d': fields.String,
                'l_d': fields.String,
                'is_today': fields.Integer
            })
        )
    }

    @marshal_with(response_fields)
    def get(self):
        logging.info('Calendar GET.')
        return get_ludar_dict(datetime.now())

    @marshal_with(response_fields)
    def post(self):
        logging.info('Calendar POST.')
        parser = reqparse.RequestParser()
        parser.add_argument('year', type=str)
        parser.add_argument('month', type=str)
        args = parser.parse_args()
        year = args['year']
        month = args['month']
        date = datetime(int(year), int(month), 1)
        return get_ludar_dict(date)
